package orderlayer

import (
	//"strconv"
	"time"
	"encoding/json"
	"dhfshop/service/event"
	"dhfshop/models/shopping"
	"github.com/astaxie/beego"
)

// 拼团交易24小时内,没有拼团成功,自动结束。
func TimeoutClosePtAct(recallMsg string) (err error) {
	type CallBackMsg struct {
		PintuanActivityId   int64 `json:"pintuan_activity_id"`
	}
	var msg CallBackMsg
	if err = json.Unmarshal([]byte(recallMsg), &msg); err != nil {
		return err
	}
	//pintuanActIdStr := strconv.FormatInt(msg.PintuanActivityId, 10)
	activity, err := shopping.GetPintuanActivityById(msg.PintuanActivityId)
	if err != nil {
	    beego.Debug("GetPintuanActivityById:", err.Error())
	    return
	}
	if activity.StartTime.Unix() - time.Now().UTC().Unix() < 24*3600 {
	    return
	}
	if activity.CurrentCustomerNum >= activity.NeedCustomerNum {
	    return           
	}
	if pintuanDeatils, err := shopping.GetPintuanDetailsByActId(msg.PintuanActivityId); err == nil {
		//订单进入售后状态，等待退款
		for _, detail := range pintuanDeatils {
		    var result string = ""
			var req = new(event.TradeMsg)
			req.CompanyId = detail.PartnerId
			req.UserId = detail.MemberId
			req.OrderId = detail.OrderId
			req.MsgHeader.EventType = "E_ORDER_SERVICE"
			message, err := event.EncodeMsg(req)
			if err != nil {
				beego.Debug(err.Error())
				continue     
			}
			event.KernelBus.Publish("E_ORDER_SERVICE", message, &result)
			if len(result) > 0 {
				beego.Debug(result)
			}
		}
	}
	return
}

// 拼团实例结束前30分钟,提醒团员去分享
func TimeoutRemaindSharePtAct(recallMsg string) (err error) {
	type CallBackMsg struct {
		PintuanActivityId   int64 `json:"pintuan_activity_id"`
	}
	var msg CallBackMsg
	if err = json.Unmarshal([]byte(recallMsg), &msg); err != nil {
		return err
	}
	//pintuanActIdStr := strconv.FormatInt(msg.PintuanActivityId, 10)
	//activity, err := shopping.GetPintuanActivityById(msg.PintuanActivityId)
	//if err != nil {
	//    beego.Debug("GetPintuanActivityById:", err.Error())
	//    return
	//}
	if pintuanDeatils, err := shopping.GetPintuanDetailsByActId(msg.PintuanActivityId); err == nil {
		for _, detail := range pintuanDeatils {
		    beego.Debug(detail.OrderId)
		}
	}
	return
}
